import { useState } from 'react';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { dispenserApi } from '../api/Api';
import { useSockJS } from './useSockJS';
import { useHttp } from './useHttp';
import { Order } from '../types';

export function useDispenser() {
  const {robotCount, idleRobotCount} = useSockJS();  // 使用自定义 Hook 获取机器人数量、消息和发送功能
  const queryClient = useQueryClient();
  
  const [deliveredOrderNumbers, setDeliveredOrderNumbers] = useState<string[]>([]);  // 用来记录已交付订单号

  const {
    data: orders = [],
    isLoading: isLoadingOrders,
  } = useQuery<Order[]>({
    queryKey: ['pendingOrders'],
    queryFn: dispenserApi.getPendingOrders,
  });

  //药品交付
  const handleDispenseMedication = async () => {
    const pendingOrderFirst = orders.find(       
      (order) => order.status === 0 && !deliveredOrderNumbers.includes(order.orderNumber)  // 过滤已交付订单
    );

    if (idleRobotCount === 0 || !pendingOrderFirst) return;

    // 更新已交付订单号数组
    setDeliveredOrderNumbers((prev) => [...prev, pendingOrderFirst.orderNumber]);

    // 执行交付操作, 发送订单号给后端
    const { sendPostRequest } = useHttp();
    const handleSendOrder = async (orderNum: string) => {
      try {
        const data = await sendPostRequest({ order_num: orderNum });
        console.log('http响应:', data);
      } catch (error) {
        console.error('http错误', error);
      }
    };
    // 调用 handleSendOrder 发送订单号
    await handleSendOrder(pendingOrderFirst.orderNumber);

    // 刷新订单数据
    queryClient.invalidateQueries({ queryKey: ['pendingOrders'] });
  };

  return {
    robotCount,
    idleRobotCount,
    pendingOrders: orders.filter(order => !deliveredOrderNumbers.includes(order.orderNumber)), // 过滤已交付的订单
    isLoading: isLoadingOrders,
    handleDispenseMedication,
  };
}
